package com.zhongkai.web.tag;

import java.net.URLEncoder;
import java.util.Enumeration;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.tagext.TagSupport;

import org.apache.log4j.Logger;

import com.zhongkai.tools.StringTool;

public class PageTag extends TagSupport {
	Logger log = Logger.getLogger(this.getClass());

	@Override
	public int doStartTag() throws JspException {
		StringBuffer UrlWhere = new StringBuffer();// url中的条件
		try {
			for (Enumeration i = pageContext.getRequest().getParameterNames(); i
					.hasMoreElements();) {
				String name = (String) i.nextElement();
				String value = pageContext.getRequest().getParameter(name);
				if (!name.equals("pageIndex")) {
					try {
						name = URLEncoder.encode(name, "UTF-8");
						value = URLEncoder.encode(value, "UTF-8");
					} catch (Exception ex) {
						log.error(ex.toString());
					}
					UrlWhere.append("&").append(name).append("=").append(value);
				}
			}
			String pageIndex = pageContext.getRequest().getParameter(
					"pageIndex");// 页数
			if (pageIndex == null || !pageIndex.matches("\\d+")) {
				pageIndex = "1";
			}
			int intPageIndex = Integer.valueOf(pageIndex).intValue();
			String pageMax = (String) pageContext.getAttribute("pageMax");
			String totalRecord = (String) pageContext
					.getAttribute("totalRecord");
			int intLastpage = 1;
			if (pageMax != null && totalRecord != null) {
				if (Integer.valueOf(totalRecord).intValue()
						% Integer.valueOf(pageMax).intValue() == 0
						&& Integer.valueOf(totalRecord).intValue() != 0) {
					intLastpage = Integer.valueOf(totalRecord).intValue()
							/ Integer.valueOf(pageMax).intValue();
				} else {
					intLastpage = Integer.valueOf(totalRecord).intValue()
							/ Integer.valueOf(pageMax).intValue() + 1;
				}
			}
			HttpServletRequest request;
			request = (HttpServletRequest) pageContext.getRequest();
			StringBuffer firstPage = new StringBuffer(request.getRequestURI())
					.append("?pageIndex=").append(1).append(UrlWhere);
			StringBuffer previousPage = new StringBuffer(request
					.getRequestURI()).append("?pageIndex=").append(
					(intPageIndex - 1)).append(UrlWhere);
			StringBuffer nextPage = new StringBuffer(request.getRequestURI())
					.append("?pageIndex=").append((intPageIndex + 1)).append(
							UrlWhere);
			StringBuffer lastPage = new StringBuffer(request.getRequestURI())
					.append("?pageIndex=").append(intLastpage).append(UrlWhere);
			
			StringTool.setPageContext(pageContext);//在StringTool中初始化PageContext,
													// 这句很重要
			StringBuffer strHTML = new StringBuffer("<p align=center>");
			strHTML.append("[<a href='").append(firstPage).append("'>").append("首页").append(
					"</a>]");
			if ("1".equals(pageIndex)) {
				strHTML.append("&nbsp;&nbsp;&nbsp;&nbsp;[").append("上一页").append(
						"]");
			} else {
				strHTML.append("&nbsp;&nbsp;&nbsp;&nbsp;[<a href='").append(
						previousPage).append("'>").append("上一页").append(
						"</a>]");
			}

			if (String.valueOf(intLastpage).equals(pageIndex)) {
				strHTML.append("&nbsp;&nbsp;&nbsp;&nbsp;[").append("下一页").append(
						"]");
			} else {
				strHTML.append("&nbsp;&nbsp;&nbsp;&nbsp;[<a href='").append(
						nextPage).append("'>").append("下一页").append(
						"</a>]");
			}

			strHTML.append("&nbsp;&nbsp;&nbsp;&nbsp;[<a href='").append(
					lastPage).append("'>").append("尾页").append(
					"</a>]");
			strHTML.append("<font color=#FF3333>&nbsp;[").append(pageIndex)
					.append("]&nbsp;</font>");
			strHTML.append("&nbsp;&nbsp;").append("跳转到").append(
					"&nbsp;&nbsp;");
			strHTML.append(
					"<script>function changeUrl(JsName){ location.replace('")
					.append(request.getRequestURI()).append(
							"?pageIndex='+JsName+'").append(UrlWhere);
			strHTML
					.append("');} </script><select name='pageSelected'  onChange='changeUrl(this.value)'>");
			for (int i = 1; i <= intLastpage; i++) {
				if (String.valueOf(i).equals(pageIndex)) {
					strHTML.append("<option selected='selected' value='")
							.append(i).append("'>").append(i).append(
									"</option>");
				} else {
					strHTML.append("<option value='").append(i).append("'>")
							.append(i).append("</option>");
				}
			}
			strHTML.append("</select>");
			strHTML.append("&nbsp; ").append("页").append(" ")
					.append("共").append(
							"&nbsp; ").append(totalRecord).append("&nbsp;")
					.append("条信息")
					.append(",").append("共").append(
							"&nbsp;").append(intLastpage).append("&nbsp; ")
					.append("页").append(
							"</p>");
			StringTool.setPageContext(null);// 用完置null
			JspWriter writer = pageContext.getOut();
			writer.println(strHTML.toString());
		} catch (Exception ex) {
			try {
				ex.printStackTrace();
				String path=((HttpServletRequest)pageContext.getRequest()).getContextPath();
				log.error(ex.getMessage());
				((HttpServletResponse) pageContext.getResponse())
						.sendRedirect(path+"/errorpage.jsp?errorinfo="
								+ java.net.URLEncoder.encode(ex.toString(),
										"UTF-8"));
			} catch (java.io.IOException ioe) {
				log.error(ioe.getMessage());
			}
		}
		return SKIP_BODY;
	}
}
